import CryptoJS from 'crypto-js'
import { PATH } from '@/config/index'
import { message } from 'ant-design-vue'

/**
 * @method guid Generate uuid
 */
export function Guid() {
  function s4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
  }
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4()
}

/**
 * @method timeFormat Format Time
 * @param {Date} time Time required for formatting
 * @param {String} format The format that needs to be formatted
 */
export function timeFormat(time: Date, format: string) {
  const [year, month, day, hour, minutes, seconds] = [
    time.getFullYear(),
    time.getMonth() + 1 >= 10 ? time.getMonth() + 1 : '0' + (time.getMonth() + 1),
    time.getDate() >= 10 ? time.getDate() : '0' + time.getDate(),
    time.getHours() >= 10 ? time.getHours() : '0' + time.getHours(),
    time.getMinutes() >= 10 ? time.getMinutes() : '0' + time.getMinutes(),
    time.getSeconds() >= 10 ? time.getSeconds() : '0' + time.getSeconds(),
  ]
  switch (format) {
    case 'Y-M-D H:M:S':
      return `${year}-${month}-${day} ${hour}:${minutes}:${seconds}`
    case 'Y/M/D H:M:S':
      return `${year}/${month}/${day} ${hour}:${minutes}:${seconds}`
    case 'Y-M-D-H-M-S':
      return `${year}-${month}-${day}-${hour}-${minutes}-${seconds}`
    case 'Y-M-D':
      return `${year}-${month}-${day}`
    case 'Y/M/D':
      return `${year}/${month}/${day}`
    case 'Y.M.D':
      return `${year}.${month}.${day}`
    case 'H:M:S':
      return hour + ':' + minutes + ':' + seconds
  }
}

// AES offset encryption
export function aesEncrypt(message: string, key: string, iv: string) {
  const keyHex = CryptoJS.enc.Utf8.parse(CryptoJS.MD5(key.toUpperCase()).toString().toUpperCase())
  const ivHex = CryptoJS.enc.Utf8.parse(iv)
  const encrypted = CryptoJS.AES.encrypt(message, keyHex, {
    iv: ivHex,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
  })
  return encrypted.toString()
}

export async function openApiFetch(
  url: string,
  ak: string,
  globalUser: string,
  body?: any,
) {
  const params = {
    method: 'post',
    headers: {},
    body: ''
  }
  if (body) params.body = JSON.stringify(body)
  params.headers = {
    'Content-Type': 'application/json',
    AccessKey: ak,
    GlobalUser: globalUser
  }
  return new Promise((resolve, reject) => {
    fetch(`${PATH}${url}`, params)
      .then((res: any) => {
        return res.json()
      })
      .then((data) => {
        if (data.success) {
          resolve(data)
        } else {
          message.error(data.code)
          reject(data)
        }
      })
      .catch(() => {
        reject()
      })
  })
}
